package com.ytxg.health_management.dict.service;

import com.ytxg.health_management.dict.mapper.NewDictMapper;
import com.ytxg.health_management.dict.pojo.Dict;
import com.ytxg.health_management.util.MyException;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class NewDictServiceImpl implements NewDictService {
    private static final Logger log = LoggerFactory.getLogger(NewDictServiceImpl.class);
    @Resource
    NewDictMapper newDictMapper;

    /**
     * 获取字典列表(条件)
     */
    @Override
    public List<Dict> getDicts(Dict dict) {
        try {
            return newDictMapper.getDicts(dict);
        } catch (Exception e) {
            throw new MyException("获取字典失败" + e);
        }
    }

    /**
     * 新增字典(条件)
     */
    @Override
    public int addDict(Dict dict) {
        dict.setCreateTime(new Date());
        try {
            return newDictMapper.addDict(dict);
        } catch (Exception e) {
            throw new MyException("新增字典失败" + e);
        }
    }
    /**
     * 修改字典(条件)
     */
    @Override
    public int updateDict(Dict dict) {
        try {
            return newDictMapper.updateDict(dict);
        } catch (Exception e) {
            throw new MyException("修改字典失败" + e);
        }
    }
    /**
     * 删除字典(条件)
     */
    @Override
    @Transactional
    public int deleteDict(Dict dict) {
        if (Objects.equals(dict.getLevel(), "1")) {
            try {
                newDictMapper.deleteDict(new Dict().setParentId(dict.getId()));
                log.info("删除子字典");
                newDictMapper.deleteDict(dict);
                log.info("删除主字典");
                return 1;
            } catch (Exception e) {
                throw new MyException("删除字典失败" + e);
            }
        }else {
            try {
                return newDictMapper.deleteDict(dict);
            } catch (Exception e) {
                throw new MyException("删除字典失败" + e);
            }
        }
    }
}
